package com.xzcs.controller.sysmgr;

import com.github.pagehelper.PageInfo;
import com.xzcs.controller.BaseController;
import com.xzcs.service.sysmgr.FileMgrService;
import com.xzcs.util.common.DateUtils;
import com.xzcs.util.web.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 后台登录
 * @author chang
 * @createDate 2015-6-23
 */
@Controller
@RequestMapping(value = "/sysmgr/file/")
public class FileMgrController extends BaseController {
	
	@Autowired
	private FileMgrService fileMgrService;
	
	@RequestMapping(value = "frame.do")
	public String frame(HttpServletRequest request) {
		request.setAttribute("startTime", DateUtils.getDay(-7, "yyyy-MM-dd"));
		request.setAttribute("endTime", DateUtils.getToday("yyyy-MM-dd"));
		return "html/sysmgr/file/frame";
	}
	
	@RequestMapping(value = "list.do")
	public void list(HttpServletRequest request, HttpServletResponse response) {
		PageInfo<Map<String, Object>> page = fileMgrService.findAttachments(request);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", page.getTotal());
		result.put("rows", page.getList());
		ResponseUtils.writeJson(result, response);
	}
	
	@RequestMapping(value = "edit.do")
	public String edit(HttpServletRequest request) {
		
		return "html/sysmgr/file/edit";
	}
	
	@RequestMapping(value = "upload.do")
	public void upload(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest)request;
		Map<String, Object> result = fileMgrService.uploadFile(mRequest);
		ResponseUtils.writeJson(result, response);
	}
	
	@RequestMapping(value = "downloadFile.do")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	int res = fileMgrService.downloadFile(request, response);
		Map<String, Object> result = new HashMap<String, Object>();
    	if (res != 1) {
			result.put("result", 0);
			result.put("msg", "文件下载失败！");
			ResponseUtils.writeJson(result, response);
		}
    }

	@RequestMapping(value = "deleteFile.do")
	public void deleteFile(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			fileMgrService.deleteFile(request);
			result.put("result", 1);
			result.put("msg", getMessage("operating.type.success"));
		} catch (Exception e) {
			result.put("result", 0);
			result.put("msg", getMessage("operating.type.error"));
		}
		ResponseUtils.writeJson(result, response);
	}
}
